package com.xxwy.http;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpServerCodec;

/**
 * 非谷歌浏览器
 * @author wy
 * @date 2020/3/5 11:17
 */
public class NettyServer {

  public static void main(String[] args) {
    NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
    NioEventLoopGroup workerGroup = new NioEventLoopGroup();

    ServerBootstrap serverBootstrap = new ServerBootstrap();
    serverBootstrap.group(bossGroup,workerGroup)
        .channel(NioServerSocketChannel.class)
        .childHandler(new ChannelInitializer<SocketChannel>() {

          @Override
          protected void initChannel(SocketChannel socketChannel) throws Exception {
            //像管道加入编解码器
            socketChannel.pipeline().addLast("HttpServerCodec", new HttpServerCodec());
            socketChannel.pipeline().addLast("MyHttpHandler", new HttpHandler());
          }
        });

    try {
      ChannelFuture future = serverBootstrap.bind(6666).sync();
      System.out.println("ok " + future.channel().localAddress());
      future.channel().closeFuture().sync();
    } catch (InterruptedException e) {
      e.printStackTrace();
    }finally {
      bossGroup.shutdownGracefully();
      workerGroup.shutdownGracefully();
    }
  }
}
